package me.zhengjie.modules.inspection.service.impl;

import me.zhengjie.modules.inspection.domain.InspectionPlan;
import me.zhengjie.modules.inspection.domain.InspectionTemplate;
import me.zhengjie.modules.inspection.domain.TInspectionTask;
import me.zhengjie.modules.inspection.repository.InspectionTemplateRepository;
import me.zhengjie.modules.inspection.repository.TInspectionTaskRepository;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderInfo;
import me.zhengjie.modules.serviceprovider.repository.TServiceproviderInfoRepository;
import me.zhengjie.modules.serviceprovider.service.TServiceproviderInfoService;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.utils.*;
import me.zhengjie.modules.inspection.repository.InspectionPlanRepository;
import me.zhengjie.modules.inspection.service.InspectionPlanService;
import me.zhengjie.modules.inspection.service.dto.InspectionPlanDTO;
import me.zhengjie.modules.inspection.service.dto.InspectionPlanQueryCriteria;
import me.zhengjie.modules.inspection.service.mapper.InspectionPlanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.*;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;

import me.zhengjie.utils.DateUtil;

/**
* @author xuyukun
* @date 2019-07-21
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class InspectionPlanServiceImpl implements InspectionPlanService {
    @Autowired
    private DictDetailRepository dictDetailRepository;
    @Autowired
    private TServiceproviderInfoRepository tServiceproviderInfoRepository;
    @Autowired
    private InspectionPlanRepository inspectionPlanRepository;
    @Autowired
    private InspectionTemplateRepository inspectionTemplateRepository;
    @Autowired
    private InspectionPlanMapper inspectionPlanMapper;
    @Autowired
    private TInspectionTaskRepository tInspectionTaskRepository;
    @Override
    public Object queryAll(InspectionPlanQueryCriteria criteria, Pageable pageable){
        Page<InspectionPlan> page = inspectionPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(inspectionPlanMapper::toDto));
    }

    @Override
    public Object queryAll(InspectionPlanQueryCriteria criteria){
        return inspectionPlanMapper.toDto(inspectionPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public InspectionPlanDTO findById(Long id) {
        Optional<InspectionPlan> inspectionPlan = inspectionPlanRepository.findById(id);
        ValidationUtil.isNull(inspectionPlan,"InspectionPlan","id",id);
        return inspectionPlanMapper.toDto(inspectionPlan.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InspectionPlanDTO create(InspectionPlan resources) {
        //巡检对象
        getObject(resources);
        //根据周期形式巡检任务，
        inspectionPlanRepository.save(resources);
        // totask(resources); TODO @@@@@
        return inspectionPlanMapper.toDto(resources);
    }

    private void totask(InspectionPlan resources) {

        List<TInspectionTask> tInspectionTaskList=new ArrayList<>();
        if (resources.getPeriodId() == 1) {
            String starttime= DateUtil.parseDateToStr(resources.getStartTime(),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
            String endtime=DateUtil.parseDateToStr(resources.getEndTime(),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
            resources.setPeriodName("日");
           List<String> stringList= DateUtil.getDayListOfDate(starttime,endtime);

            for(String dateStr:stringList){
                TInspectionTask tInspectionTask=new TInspectionTask();
                Date end=DateUtil.parseStrToDate((dateStr+" 23:59:59"),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                Timestamp tsEnd = new Timestamp(end.getTime());
                tInspectionTask.setEndTime(tsEnd);
                tInspectionTask.setInspectorId(resources.getInspectorId());
                tInspectionTask.setInspectorName(resources.getInspectorName());
                tInspectionTask.setObjId(resources.getObjId());
                tInspectionTask.setObjName(resources.getObjName());
                tInspectionTask.setPeriodId(resources.getPeriodId());
                tInspectionTask.setPeriodName(resources.getPeriodName());
                Date strat=DateUtil.parseStrToDate(dateStr+" 00:00:00",DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                Timestamp tsStr = new Timestamp(strat.getTime());
                tInspectionTask.setStartTime(tsStr);
                tInspectionTask.setTemplateId(resources.getTemplateId());
                tInspectionTask.setTemplateName(resources.getTemplateName());
                tInspectionTask.setPlanName(resources.getPlanName());
                tInspectionTask.setPlanid(resources.getId());
                tInspectionTask.setVehTypeId(resources.getVehTypeId());
                tInspectionTask.setVehTypeName(resources.getVehTypeName());
                tInspectionTaskList.add(tInspectionTask);
            }
        } else if (resources.getPeriodId() == 2) {
            resources.setPeriodName("周");
            Date starttime=DateUtil.parseStrToDate(DateUtil.parseTimestampToStr(resources.getStartTime(),DateUtil.DATE_FORMAT_YYYY_MM_DD),DateUtil.DATE_FORMAT_YYYY_MM_DD);
            Date endtime=DateUtil.parseStrToDate(DateUtil.parseTimestampToStr(resources.getEndTime(),DateUtil.DATE_FORMAT_YYYY_MM_DD),DateUtil.DATE_FORMAT_YYYY_MM_DD);
            List<String[]> result= DateUtil.getType(starttime,endtime);
            for (int i = 0; i < result.size(); i++) {
                String list[] = result.get(i);

                String startStr=list[0];
                String endStr=list[1];
                TInspectionTask tInspectionTask=new TInspectionTask();
                Date end=DateUtil.parseStrToDate((endStr+" 23:59:59"),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                Timestamp tsEnd = new Timestamp(end.getTime());
                tInspectionTask.setEndTime(tsEnd);
                tInspectionTask.setInspectorId(resources.getInspectorId());
                tInspectionTask.setInspectorName(resources.getInspectorName());
                tInspectionTask.setObjId(resources.getObjId());
                tInspectionTask.setObjName(resources.getObjName());
                tInspectionTask.setPeriodId(resources.getPeriodId());
                tInspectionTask.setPeriodName(resources.getPeriodName());
                Date strat=DateUtil.parseStrToDate(startStr+" 00:00:00",DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                Timestamp tsStr = new Timestamp(strat.getTime());
                tInspectionTask.setStartTime(tsStr);
                tInspectionTask.setTemplateId(resources.getTemplateId());
                tInspectionTask.setTemplateName(resources.getTemplateName());
                tInspectionTask.setPlanName(resources.getPlanName());
                tInspectionTask.setPlanid(resources.getId());
                tInspectionTask.setVehTypeId(resources.getVehTypeId());
                tInspectionTask.setVehTypeName(resources.getVehTypeName());
                tInspectionTaskList.add(tInspectionTask);
            }
        } else if (resources.getPeriodId() == 3) {

            resources.setPeriodName("月");
            String starttime= DateUtil.parseTimestampToStr(resources.getStartTime(),DateUtil.DATE_FORMAT_YYYY_MM_DD);
            String endtime=DateUtil.parseTimestampToStr(resources.getEndTime(),DateUtil.DATE_FORMAT_YYYY_MM_DD);
            List<KeyValueForDate> keyValueForDates= DateUtil.getKeyValueForDate(starttime,endtime);
            for(KeyValueForDate keyValueForDate:keyValueForDates){
                TInspectionTask tInspectionTask=new TInspectionTask();
                Date end=DateUtil.parseStrToDate((keyValueForDate.getEndDate()+" 23:59:59"),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                Timestamp tsEnd = new Timestamp(end.getTime());
                tInspectionTask.setEndTime(tsEnd);
                tInspectionTask.setInspectorId(resources.getInspectorId());
                tInspectionTask.setInspectorName(resources.getInspectorName());
                tInspectionTask.setObjId(resources.getObjId());
                tInspectionTask.setObjName(resources.getObjName());
                tInspectionTask.setPeriodId(resources.getPeriodId());
                tInspectionTask.setPeriodName(resources.getPeriodName());
                Date strat=DateUtil.parseStrToDate(keyValueForDate.getStartDate()+" 00:00:00",DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                Timestamp tsStr = new Timestamp(strat.getTime());
                tInspectionTask.setStartTime(tsStr);
                tInspectionTask.setTemplateId(resources.getTemplateId());
                tInspectionTask.setTemplateName(resources.getTemplateName());
                tInspectionTask.setPlanName(resources.getPlanName());
                tInspectionTask.setPlanid(resources.getId());
                tInspectionTask.setVehTypeId(resources.getVehTypeId());
                tInspectionTask.setVehTypeName(resources.getVehTypeName());
                tInspectionTaskList.add(tInspectionTask);
            }
        } else if (resources.getPeriodId() == 4) {
            resources.setPeriodName("季");
            String starttime= DateUtil.parseTimestampToStr(resources.getStartTime(),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
            String endtime=DateUtil.parseTimestampToStr(resources.getEndTime(),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
            List<Map<String, String>> mapList=null;
            try {
                mapList=DateUtil.queryInterval( starttime,  endtime, 2);
                if(!CollectionUtils.isEmpty(mapList)){
                    for(Map<String, String> map:mapList){
                        System.out.println(map);
                        TInspectionTask tInspectionTask=new TInspectionTask();
                        Date end=DateUtil.parseStrToDate(map.get("end"),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                        Timestamp tsEnd = new Timestamp(end.getTime());
                        tInspectionTask.setEndTime(tsEnd);
                        tInspectionTask.setInspectorId(resources.getInspectorId());
                        tInspectionTask.setInspectorName(resources.getInspectorName());
                        tInspectionTask.setObjId(resources.getObjId());
                        tInspectionTask.setObjName(resources.getObjName());
                        tInspectionTask.setPeriodId(resources.getPeriodId());
                        tInspectionTask.setPeriodName(resources.getPeriodName());
                        Date strat=DateUtil.parseStrToDate(map.get("start"),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                        Timestamp tsStr = new Timestamp(strat.getTime());
                        tInspectionTask.setStartTime(tsStr);
                        tInspectionTask.setTemplateId(resources.getTemplateId());
                        tInspectionTask.setTemplateName(resources.getTemplateName());
                        tInspectionTask.setPlanName(resources.getPlanName());
                        tInspectionTask.setPlanid(resources.getId());
                        tInspectionTask.setVehTypeId(resources.getVehTypeId());
                        tInspectionTask.setVehTypeName(resources.getVehTypeName());
                        tInspectionTaskList.add(tInspectionTask);
                    }
                }
            } catch (ParseException e) {

            }
        } else if (resources.getPeriodId() == 5) {
            resources.setPeriodName("半年");
        } else if (resources.getPeriodId() == 6) {
            resources.setPeriodName("年");
            String starttime= DateUtil.parseTimestampToStr(resources.getStartTime(),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
            String endtime=DateUtil.parseTimestampToStr(resources.getEndTime(),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
            List<Map<String, String>> mapList=null;
            try {
                mapList=DateUtil.queryInterval( starttime,  endtime, 3);
                if(!CollectionUtils.isEmpty(mapList)){
                    for(Map<String, String> map:mapList){
                        System.out.println(map);
                        TInspectionTask tInspectionTask=new TInspectionTask();
                        Date end=DateUtil.parseStrToDate(map.get("end"),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                        Timestamp tsEnd = new Timestamp(end.getTime());
                        tInspectionTask.setEndTime(tsEnd);
                        tInspectionTask.setInspectorId(resources.getInspectorId());
                        tInspectionTask.setInspectorName(resources.getInspectorName());
                        tInspectionTask.setObjId(resources.getObjId());
                        tInspectionTask.setObjName(resources.getObjName());
                        tInspectionTask.setPeriodId(resources.getPeriodId());
                        tInspectionTask.setPeriodName(resources.getPeriodName());
                        Date strat=DateUtil.parseStrToDate(map.get("start"),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                        Timestamp tsStr = new Timestamp(strat.getTime());
                        tInspectionTask.setStartTime(tsStr);
                        tInspectionTask.setTemplateId(resources.getTemplateId());
                        tInspectionTask.setTemplateName(resources.getTemplateName());
                        tInspectionTask.setPlanName(resources.getPlanName());
                        tInspectionTask.setPlanid(resources.getId());
                        tInspectionTask.setVehTypeId(resources.getVehTypeId());
                        tInspectionTask.setVehTypeName(resources.getVehTypeName());
                        tInspectionTaskList.add(tInspectionTask);
                    }
                }
            } catch (ParseException e) {

            }
        }
        tInspectionTaskRepository.saveAll(tInspectionTaskList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(InspectionPlan resources) {
        Optional<InspectionPlan> optionalInspectionPlan = inspectionPlanRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalInspectionPlan,"InspectionPlan","id",resources.getId());

        InspectionPlan inspectionPlan = optionalInspectionPlan.get();
        // 此处需自己修改
        resources.setId(inspectionPlan.getId());
        getObject(resources);
        inspectionPlanRepository.save(resources);
    }

    private void getObject(InspectionPlan resources) {
        //巡检对象
        /*DictDetail dictDetailObjDTO = dictDetailRepository.findById(resources.getObjId()).get();
        if (dictDetailObjDTO != null) {
            resources.setObjName(dictDetailObjDTO.getLabel());
        }*/
        //巡检模板
        /*InspectionTemplate inspectionTemplate = inspectionTemplateRepository.findById(resources.getTemplateId()).get();
        if (inspectionTemplate != null) {
            resources.setTemplateName(inspectionTemplate.getTemplateName());
        }*/
        //巡检工具
        /*DictDetail dictDetailToolDTO = dictDetailRepository.findById(resources.getToolId()).get();
        if (dictDetailToolDTO != null) {
            resources.setToolName(dictDetailToolDTO.getLabel());
        }*/
        //服务商
        TServiceproviderInfo tServiceproviderInfoDTO = tServiceproviderInfoRepository.findById(resources.getInspectorId()).get();
        if (tServiceproviderInfoDTO != null) {
            resources.setInspectorName(tServiceproviderInfoDTO.getSeproName());
        }
        //巡检车辆
        //巡检模板
        /*DictDetail dictDetailVehDTO = dictDetailRepository.findById(resources.getVehTypeId()).get();
        if (dictDetailVehDTO != null) {
            resources.setVehTypeName(dictDetailVehDTO.getLabel());
        }*/

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        inspectionPlanRepository.deleteById(id);
    }
}